﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace XingLucifer.Devices.Devices
{
    //[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public class Live20R
    {
        private IntPtr _mDevHandle;
        private IntPtr _mDBHandle;
        #region 托管函数
        [DllImport("libzkfp.dll")]
        private static extern int ZKFPM_Init();
        [DllImport("libzkfp.dll")]
        private static extern int ZKFPM_GetDeviceCount();
        [DllImport("libzkfp.dll")]
        private static extern int ZKFPM_Terminate();
        [DllImport("libzkfp.dll")]
        private static extern IntPtr ZKFPM_OpenDevice(int index);

        [DllImport("libzkfp.dll")]
        private static extern int ZKFPM_CloseDevice(IntPtr handle);

        [DllImport("libzkfp.dll")]
        private static extern IntPtr ZKFPM_CreateDBCache();

        [DllImport("libzkfp.dll")]
        private static extern int ZKFPM_AcquireFingerprint(IntPtr handle, byte[] fpImage, uint cbFPImage, byte[] fpTemplate, ref int cbTemplate);

        #endregion

        public Live20R()
        {

        }

        public bool Connect()
        {
            bool flag = ZKFPM_Init() == 0;
            if (!flag) { Log("初始化失败"); return false; }
            flag = ZKFPM_GetDeviceCount() <= 0;
            if(flag) { ZKFPM_Terminate(); Log("找不到设备"); return false; }
            _mDevHandle = ZKFPM_OpenDevice(0);
            if (_mDevHandle != IntPtr.Zero)
            {
                _mDBHandle = ZKFPM_CreateDBCache();
                return _mDBHandle != IntPtr.Zero;
            }
            Log("设备为空");
            return false;
        }

        public bool Disconnect()
        {
            if (_mDevHandle != IntPtr.Zero)
            {
                ZKFPM_CloseDevice(_mDevHandle);
                ZKFPM_Terminate();
            }
            return true;
        }
        private void Log(string msg)
        {
            System.IO.File.WriteAllText(".\\length.txt", msg);
        }

        public string GetImage()
        {
            if (IntPtr.Zero == _mDevHandle)
            {
                return default;
            }
            byte[] img_buffer = new byte[120000];
            byte[] template = new byte[2048];
            int size = 2048;
            int ret = ZKFPM_AcquireFingerprint(_mDevHandle, img_buffer, (uint)img_buffer.Length, template, ref size);
            if (ret == 0)
            {
                return Convert.ToBase64String(template, 0, template.Length, Base64FormattingOptions.None);
            }
            return default;
        }
    }
}
